#include <iostream>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>

using namespace std;
typedef websocketpp::server<websocketpp::config::asio> server_t;
typedef server_t::message_ptr message_ptr;

using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;

void OnOpen(server_t *server,websocketpp::connection_hdl hdl){
    cout<<"连接成功"<<endl;
}

void OnClose(server_t *server,websocketpp::connection_hdl hdl){
    cout<<"连接关闭"<<endl;
}

void OnMessage(server_t *server,websocketpp::connection_hdl hdl,message_ptr msg){
    cout<<"收到消息"<<msg->get_payload()<<endl;
    //收到消息后将消息返回给websocket客户端
    server->send(hdl,msg->get_payload(),websocketpp::frame::opcode::text);
}

void OnFail(server_t *server,websocketpp::connection_hdl hdl){
    cout<<"连接异常"<<endl;
}

//处理http请求的回调函数，返回一个html欢迎页面
void OnHttp(server_t *server,websocketpp::connection_hdl hdl){

    cout<<"处理http请求"<<endl;
    server_t::connection_ptr conn = server->get_con_from_hdl(hdl);
    std::stringstream ss;
    ss << "<!doctype html><html><head>"
    << "<title>hello websocket</title><body>"
    << "<h1>hello websocketpp</h1>"
    << "</body></head></html>";
    conn->set_body(ss.str());
    conn->set_status(websocketpp::http::status_code::ok);

}

int main(){
    //创建服务器
    server_t server;
    //设置日志级别
    server.set_access_channels(websocketpp::log::alevel::none);
    //初始化asio
    server.init_asio();
    //注册http请求的处理函数
    server.set_http_handler(bind(&OnHttp,&server,::_1));
    //这个预测websocket请求的处理函数
    server.set_open_handler(bind(&OnOpen,&server,::_1));
    server.set_close_handler(bind(&OnClose,&server,::_1));
    server.set_message_handler(bind(&OnMessage,&server,_1,_2));


    //监听9999端口
    server.listen(9999);
    //开始接收tcp连接
    server.start_accept();
    //开始运行服务器
    server.run();



    return 0;
}